package com.groot.medical.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.groot.common.controller.BaseServletController;
import com.groot.medical.entity.AdministrativeArea;
import com.groot.medical.entity.Menu;
import com.groot.medical.entity.PageBean;
import com.groot.medical.entity.Role;
import com.groot.medical.entity.SysUser;
import com.groot.medical.entity.UserRole;
import com.groot.medical.service.AdministrativeAreaService;
import com.groot.medical.service.AdministrativeAreaServiceImpl;
import com.groot.medical.service.RoleService;
import com.groot.medical.service.RoleServiceImpl;
import com.groot.medical.service.UserService;
import com.groot.medical.service.UserServiceImpl;
@WebServlet("/sys/user.do")
public class UserConctroller extends BaseServletController {
	
	private static final long serialVersionUID = 1L;
	private UserService userService = new UserServiceImpl();
	private RoleService roleService = new RoleServiceImpl();
	private AdministrativeAreaService areaService = new AdministrativeAreaServiceImpl();
	
	private static Logger LOGGER = Logger.getLogger(LoginController.class);
	
	public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LOGGER.info("this is @WebServlet(\"/index.do\").execute()");
		return null;
	}
	
	/*
	 * 打开添加页面
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String openAddUser(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		//查询所有角色信息
		List<Role> roleList = roleService.findAllRoleList();
		//查询行政区域（县，镇）
		List<AdministrativeArea> area = areaService.findContryAndTown();
		request.setAttribute("roleList", roleList);
		request.setAttribute("area", area);
		request.setAttribute("tgId",request.getParameter("tgId"));
		return "/WEB-INF/page/user/adduser.jsp";
	}
	/**
	 * 添加用户
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String addUser(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		String [] roleIds = request.getParameterValues("roleIdList");
		System.out.println(roleIds);
		String userid = request.getParameter("userid");
		String password = request.getParameter("password");
		String username = request.getParameter("username");
		String areacode=request.getParameter("areacode");
		String tgId = request.getParameter("tgId");
		String pageNum = request.getParameter("pageNum");
		SysUser sysUser = new SysUser();
		sysUser.setUserId(userid);
		sysUser.setUsername(username);
		sysUser.setPassword(password);
		sysUser.setAreaCode(areacode);
		
		int i = userService.addUser(roleIds,sysUser);
		if(i==1){
			request.setAttribute("msg", "<script>alert('修改成功')</script>");
			return findUserByPage(request,response);
		
		}else
			LOGGER.info("添加失败"+i);
		response.sendRedirect("user.do?method=findAllUserList");
		return null;
	}
	/**
	 * 打开用户修改页面
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String openEditUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String userid = request.getParameter("userid");
		
		LOGGER.info("用户userid："+userid);
		//用户id查询用户信息
		SysUser sysUser = userService.findUserById(userid);
		//查询所有角色
		List<Role> roleList = roleService.findAllRoleList();
		request.setAttribute("roleList", roleList);
		//查询改用户已拥有的角色
		List<UserRole> alreadyHaveRole = roleService.findRoleByUserId(userid);
		System.out.println("alreadyHaveRole:::"+alreadyHaveRole);
		request.setAttribute("alreadyHaveRole", alreadyHaveRole);
		LOGGER.info("用户信息"+sysUser);
		request.setAttribute("sysUser", sysUser);
		request.setAttribute("tgId",request.getParameter("tgId"));
		return "/WEB-INF/page/user/edituser.jsp";

	}
	/**
	 * 修改用户信息
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String editUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String userid = request.getParameter("userid");
		String password = request.getParameter("password");
		String username = request.getParameter("username");
		String tgId = request.getParameter("tgId");
		String pageNum = request.getParameter("pageNum");
		String [] roleIdList = request.getParameterValues("roleIdList");
		
		SysUser sysUser = new SysUser();
		sysUser.setUserId(userid);
		sysUser.setUsername(username);
		sysUser.setPassword(password);
		//先删除该用户拥有的角色信息
		userService.delUserRole(userid);
		//再重新给用户赋予角色
		int i = userService.editUser(roleIdList,sysUser);
		if(i==1){
			LOGGER.info("修改成功"+i);
			
			
			
			return findUserByPage(request,response);
		}else
			LOGGER.info("修改失败"+i);
		response.sendRedirect("user.do?method=findAllUserList");
		return null;
		
		}
	/**
	 * 赋予用户角色
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String giveRoleToUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			String  userid = request.getParameter("userid");
			SysUser sysUser = userService.findUserById(userid);
		return null;
	}
	/**
	 * 分页查询用户信息
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String findUserByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int pageNum = Integer.valueOf(request.getParameter("pageNum"));
		//获取页面传来的权限id
		String tgId = request.getParameter("tgId");
		//从session中取出
		List<Menu> menus=(List<Menu>) request.getSession().getAttribute("menuList");
		List<Menu> result = new ArrayList<Menu>();
		/*根据页面传过来的id与该用户所有权限的上一级id比较
		 * 若该权限的上一级传过来的id相同则存入新集合
		 */
		for(Menu menu: menus){
			if(menu.getMenuPid().equals(tgId)){
				result.add(menu);
			}
		}
		System.out.println("result我要他的："+result);
		Gson gson = new Gson();
		request.setAttribute("resultMenus", gson.toJson(result));
		request.setAttribute("tgId", tgId);
		
		int pageSize = 5;
		PageBean userPage = userService.findByPage(pageNum, pageSize);
		System.out.println("userPage:"+userPage);
		request.setAttribute("pageBean", userPage);



		return "/WEB-INF/page/user/user_list.jsp";
	}
	/**
	 * 检验用户是否存在
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public void CheckIdExist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("Id");
		System.out.println("_+_++_+::::::_+_："+id);
		SysUser user = userService.findUserById(id);
		
		String resultString = "true";
        if (user!=null ){
            resultString = "false";
        }
		response.setContentType("text/html");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(resultString.getBytes());
        outputStream.close();


		/*PrintWriter pw = response.getWriter();
		Map<String, String> map = new HashMap<>();
		if (user!=null) {
            //说明账号存在
			map.put("res", "用户名已经存在");
        }
		else{
            map.put("res", "可以使用");
        }
        //返回json格式的字符串给浏览器
		Gson json = new Gson();
        pw.print(json.toJson(map));
        pw.flush();
        pw.close();*/

			
		
	}
	/**
	 * 删除用户
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public void deleteUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String userid = request.getParameter("userid");
		String resultString = "false";
		//判断是否在存在 业务操作
		//删除用户信息
		int flag=userService.deleteUserByUserId(userid);
		System.out.println("哇哇哇"+flag);
		if(flag>0){
			resultString = "false";
			response.setContentType("text/html");
	        ServletOutputStream outputStream = response.getOutputStream();
	        outputStream.write(resultString.getBytes());
	        outputStream.close();
		}else{
			
			resultString = "true";
			response.setContentType("text/html");
	        ServletOutputStream outputStream = response.getOutputStream();
	        outputStream.write(resultString.getBytes());
	        outputStream.close();
		}
	
	}
		
}
